package com.etc.controller;

import com.etc.entity.CommentResult;
import com.etc.entity.Infobar;
import com.etc.service.InfobarService;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class InfobarController {
    @Autowired
    private InfobarService infobarService;

    @Value(value = "${imageupload.path}")
    private String uploadPath;

    @RequestMapping(value = "infobar/insert",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public CommentResult insert(@RequestPart(value = "file",required = false) MultipartFile file,
                                String info,
                                Integer park_id,
                                @RequestParam(value = "upload_date",required = false) String upload_date){
        String img = null;
        if (upload_date!=null){
            Date date = new Date();
            try {
                date = new SimpleDateFormat("yyyy-MM-dd").parse(upload_date);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Infobar infobar = new Infobar(null,info,park_id,null,date);
        }
        Infobar infobar = new Infobar(null,info,park_id,null,new Date());
        if (!file.isEmpty()){
            String fileName = file.getOriginalFilename();
            String code = UUID.randomUUID().toString().replaceAll("-", "");
            String newFileName = code + fileName.substring(fileName.lastIndexOf('.'));
            String currentDateFolder = DateFormatUtils.format(new Date(),"yyyyMMdd");
            img = uploadPath + File.separator + currentDateFolder + File.separator + newFileName;
            String uploadUrl = "imageUpload" + File.separator + currentDateFolder + File.separator + newFileName;


            try {
                File destFile = new File(img);
                if (!destFile.getParentFile().exists()) {
                    destFile.getParentFile().mkdirs();
                }
                file.transferTo(destFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            infobar.setImg(uploadUrl);
        }
        int result = infobarService.insert(infobar);
        if (result>0)
            return new CommentResult(200,"success!");
        else {
            return new CommentResult(444, "failed!");
        }
    }
}
